package com.diancan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.Utils.MenuUtils;
import com.declare.Declare;
import com.mode.CategoryObj;
import com.mode.FlipDatasource;
import com.mode.FlipItemView;
import com.mode.MenuObj;
import com.mode.SelectedMenuObj;
import com.model.Category;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class MenuFlipPage extends Activity implements OnGestureListener {
	
	private ViewFlipper flipper;
	private Handler handler = new Handler();
	private GestureDetector detector;
	List<SelectedMenuObj> menuList;
	List<CategoryObj> m_arr;
	int index;
	int rindex;
	Declare declare;
	List<FlipItemView> viewList;
	ImageView topImg;
	ImageView bottomImg;
	ImageView littleImage;
	int sWidth;
	int sHeight;
	boolean isResume;
	View waitView;
	RelativeLayout contentLayout;
	TextView categoryNameTextView;
	TextView categoryNameTextView1;
	TextView categoryNameTextView2;
	RelativeLayout nameLayout1;
	RelativeLayout nameLayout2;
	RelativeLayout categoryLayout;
	int viewCount;
	int[] idarray=new int[]{R.drawable.c1,R.drawable.c2};
	boolean isFling=false;//是否触发了滑动事件
	
	public ExecutorService executorService = Executors
			.newFixedThreadPool(3);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menuflippage);
		declare=(Declare)getApplicationContext();
		detector = new GestureDetector(this);
		contentLayout=(RelativeLayout)findViewById(R.id.contentLayout);
		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01);
		categoryNameTextView=(TextView)findViewById(R.id.categoryname);
		categoryNameTextView.setVisibility(View.INVISIBLE);
		categoryNameTextView1=(TextView)findViewById(R.id.categoryname1);
		categoryNameTextView2=(TextView)findViewById(R.id.categoryname2);
		categoryLayout=(RelativeLayout)findViewById(R.id.catLayout);
		nameLayout1=(RelativeLayout)findViewById(R.id.catLayout1);
		nameLayout2=(RelativeLayout)findViewById(R.id.catLayout2);
		
		topImg=(ImageView)findViewById(R.id.imgtop);
		topImg.setOnClickListener(new TopImgClick());
		bottomImg=(ImageView)findViewById(R.id.imgbottom);
		bottomImg.setOnClickListener(new BottomImgClick());
		littleImage=(ImageView)findViewById(R.id.imglittle);
		viewList=new ArrayList<FlipItemView>(); 
		//屏幕尺寸容器
		DisplayMetrics dm;
		dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		sWidth = dm.widthPixels;
		sHeight=dm.heightPixels;
		BitmapFactory.Options options=new BitmapFactory.Options();
		options.inSampleSize=3;
		Bitmap topBitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.top,options);
		topBitmap=Bitmap.createScaledBitmap(topBitmap, sWidth, 90, false);
		topImg.setImageBitmap(topBitmap);
		Bitmap bottomBitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.bottom,options);
		bottomBitmap=Bitmap.createScaledBitmap(bottomBitmap, sWidth, 90, false);
		bottomImg.setImageBitmap(bottomBitmap);
		m_arr=declare.getMenuListDataObj().getCategoryObjs();
		waitView=createWaitView();
		
		Intent intent =getIntent();
		index=Integer.parseInt((String)intent.getSerializableExtra("index"));
		rindex=Integer.parseInt((String)intent.getSerializableExtra("rindex"));
		System.out.println(""+index);
		System.out.println(""+rindex);
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub	
		isResume=true;
		
		AddViewToFlipper(index);
		
		super.onResume();
	}
	private void AddViewToFlipper(int i) {
		if (isResume) {
			flipper.removeAllViews();
			flipper.addView(waitView);
		}
		BitmapFactory.Options options=new BitmapFactory.Options();
		options.inSampleSize=3;	
		Bitmap tBitmap;
		Bitmap bBitmap;	
		
		CategoryObj categoryObj=m_arr.get(i);
		String cidString=categoryObj.getId()+"";
		categoryNameTextView.setVisibility(View.VISIBLE);
		categoryNameTextView.setText(categoryObj.getName());
		if(i==0)
		{
			CategoryObj categoryObj1=m_arr.get(i+1);
			tBitmap=BitmapFactory.decodeResource(getResources(), idarray[0],options);
			bBitmap=MenuUtils.GetCategoryBitMap(categoryObj1.getId()+"");
			tBitmap=Bitmap.createScaledBitmap(tBitmap, sWidth, 90, false);
			bBitmap=Bitmap.createScaledBitmap(bBitmap, sWidth, 90, false);			
			BitmapDrawable bd1= new BitmapDrawable(this.getResources(), tBitmap);
			BitmapDrawable bd2= new BitmapDrawable(this.getResources(), bBitmap);
			topImg.setBackgroundDrawable(bd1);
			bottomImg.setBackgroundDrawable(bd2);
			topImg.setAlpha(20);
			bottomImg.setAlpha(125);
			
			nameLayout1.setVisibility(View.INVISIBLE);
			nameLayout2.setVisibility(View.VISIBLE);
			categoryNameTextView2.setText(categoryObj1.getName());	
		}
		else if(i==m_arr.size()-1)
		{
			CategoryObj categoryObj1=m_arr.get(i-1);
			bBitmap=BitmapFactory.decodeResource(getResources(), idarray[1],options);
			tBitmap=MenuUtils.GetCategoryBitMap(categoryObj1.getId()+"");
			tBitmap=Bitmap.createScaledBitmap(tBitmap, sWidth, 90, false);
			bBitmap=Bitmap.createScaledBitmap(bBitmap, sWidth, 90, false);			
			BitmapDrawable bd1= new BitmapDrawable(this.getResources(), tBitmap);
			BitmapDrawable bd2= new BitmapDrawable(this.getResources(), bBitmap);
			topImg.setBackgroundDrawable(bd1);
			bottomImg.setBackgroundDrawable(bd2);
			topImg.setAlpha(125);
			bottomImg.setAlpha(20);
			nameLayout1.setVisibility(View.VISIBLE);
			nameLayout2.setVisibility(View.INVISIBLE);
			categoryNameTextView1.setText(categoryObj1.getName());
		}
		else {
			CategoryObj categoryObj1=m_arr.get(i-1);
			CategoryObj categoryObj2=m_arr.get(i+1);
			tBitmap=MenuUtils.GetCategoryBitMap(categoryObj1.getId()+"");
			bBitmap=MenuUtils.GetCategoryBitMap(categoryObj2.getId()+"");
			tBitmap=Bitmap.createScaledBitmap(tBitmap, sWidth, 90, false);
			bBitmap=Bitmap.createScaledBitmap(bBitmap, sWidth, 90, false);			
			BitmapDrawable bd1= new BitmapDrawable(this.getResources(), tBitmap);
			BitmapDrawable bd2= new BitmapDrawable(this.getResources(), bBitmap);
			topImg.setBackgroundDrawable(bd1);
			bottomImg.setBackgroundDrawable(bd2);
			topImg.setAlpha(125);
			bottomImg.setAlpha(125);
			nameLayout1.setVisibility(View.VISIBLE);
			nameLayout2.setVisibility(View.VISIBLE);		
			categoryNameTextView1.setText(categoryObj1.getName());
			categoryNameTextView2.setText(categoryObj2.getName());
		}
		menuList=categoryObj.getSelectedMenuObjs();	
//		viewList=categoryObj.getMenuViews();
		FlashUITask dTask = new FlashUITask();  
        dTask.execute(100);
//		if(declare.getMenuListDataObj().getHashMenuList().containsKey(cidString))
//		{
//			
//		}
//		else {
//			flipper.removeAllViews();
//			flipper.addView(waitView);
//			isFling=false;
//		}
	}
	private View createWaitView() {
		RelativeLayout contentLayout=new RelativeLayout(this);
		contentLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		contentLayout.setGravity(Gravity.CENTER);
		
		ImageView bigImageView=new ImageView(this);
		bigImageView.setLayoutParams(new LayoutParams(sWidth,sHeight-310));
		contentLayout.addView(bigImageView);
		BitmapFactory.Options options=new BitmapFactory.Options();
		options.inSampleSize=3;
		Bitmap bmpBitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.waitback,options);
		bmpBitmap=Bitmap.createScaledBitmap(bmpBitmap, sWidth, sHeight-310, false);
		bigImageView.setImageBitmap(bmpBitmap);
		ProgressBar progressBar = new ProgressBar(this);
		RelativeLayout.LayoutParams lParams=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		lParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        contentLayout.addView(progressBar, lParams);
		return contentLayout;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		boolean b=false;
		//没有滑动事件在响应的时候再触发滑动
		if (!isFling) {
			b = this.detector.onTouchEvent(event);
		}
		return b;
	}
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getY()>90&&e1.getY()<sHeight-220&&e2.getY()>90&&e2.getY()<sHeight-220) {
			//左右滑动
			if (e1.getX() - e2.getX() > 120) {
				isFling=true;
				this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
						R.anim.push_left_in));
				this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
						R.anim.push_left_out));
				this.flipper.showNext();
				isFling=false;
				AddFlipItemView();						
				return true;
			} else if (e1.getX() - e2.getX() < -120) {
				isFling=true;
				View cView = this.flipper.getCurrentView();
				int cindex=this.flipper.indexOfChild(cView);
				if(menuList.size()==viewList.size()||cindex!=0)
				{
					this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
							R.anim.push_right_in));
					this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
							R.anim.push_right_out));
					this.flipper.showPrevious();
				}
				isFling=false;
				return true;
			}
			//上下滑动
			else if (e1.getY() - e2.getY() > 120) {
				System.out.println("向上");
				isFling=true;
				index++;
				if (index < m_arr.size()) {
					isResume = false;
					viewCount = this.flipper.getChildCount();
					View cView = this.flipper.getCurrentView();
					if (!cView.equals(waitView)) {
						int num = this.flipper.indexOfChild(cView);
						num++;
						this.flipper.addView(waitView, num);
						viewCount++;
					}
					
					this.flipper.setInAnimation(AnimationUtils.loadAnimation(
							this, R.anim.push_top_in));
					this.flipper.setOutAnimation(AnimationUtils.loadAnimation(
							this, R.anim.push_top_out));
					this.flipper.showNext();
					categoryLayout.startAnimation(AnimationUtils.loadAnimation(
							this, R.anim.push_top_in));
					AddViewToFlipper(index);
				} else {
					isFling=false;
					index = m_arr.size() - 1;
				}

			} else if (e1.getY() - e2.getY() < -120) {
				System.out.println("向下");
				isFling=true;
				index--;
				if (index >= 0) {
					isResume = false;
					viewCount = this.flipper.getChildCount();
					View cView = this.flipper.getCurrentView();
					if (!cView.equals(waitView)) {
						int num = this.flipper.indexOfChild(cView);
						num++;
						this.flipper.addView(waitView, num);
						viewCount++;
					}
					this.flipper.setInAnimation(AnimationUtils.loadAnimation(
							this, R.anim.push_bottom_in));
					this.flipper.setOutAnimation(AnimationUtils.loadAnimation(
							this, R.anim.push_bottom_out));
					this.flipper.showNext();
					categoryLayout.startAnimation(AnimationUtils.loadAnimation(
							this, R.anim.push_bottom_out));
					AddViewToFlipper(index);
				} else {
					isFling=false;
					index = 0;
				}
			}
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	//异步加载单个FlipItemView
	public void AddFlipItemView()
	{
		if(viewList.size()<menuList.size())
		{
			executorService.submit(new Runnable() {
				 public void run() {
					 handler.post(new Runnable() {
						 public void run() {
							 SelectedMenuObj menuInfo = menuList.get(viewList.size());
								FlipItemView view=new FlipItemView(MenuFlipPage.this,menuInfo,sWidth,sHeight-310,R.drawable.addimg,R.drawable.deleteimg,littleImage,viewList.size()+1,menuList.size());
								viewList.add(view);
								MenuFlipPage.this.flipper.addView(view);
						 }
					 });
				 }
			});		
		}		
	}
	//异步加载多个FlipItemview
	class FlashUITask extends AsyncTask<Integer, Integer, String>{	

		@Override
		protected String doInBackground(Integer... params) {
			// TODO Auto-generated method stub
//			try {
//				Thread.sleep(300);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			viewList.clear();
			int i=0;
			Iterator<SelectedMenuObj> iterator;
			for (iterator = menuList.iterator(); iterator.hasNext();) {
				SelectedMenuObj menuInfo = iterator.next();
				FlipItemView view=new FlipItemView(MenuFlipPage.this,menuInfo,sWidth,sHeight-310,R.drawable.addimg,R.drawable.deleteimg,littleImage,i+1,menuList.size());
				viewList.add(view);
				publishProgress(i);
				if(i==3)
				{
					return i+"";
				}
				i++;
			}
			return i+"";
//			if(viewList.size()==0)
//			{
//				
//			}
//			else {
//				int i=0;
//				for(FlipItemView view:viewList)
//				{
//					publishProgress(i);
//					i++;
//				}
//				return i+"";
//			}
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			View v=viewList.get(values[0]);
			flipper.addView(v);
			super.onProgressUpdate(values);
		}
		@Override
		protected void onPostExecute(String result) {
			isFling=false;
			if(result.equals("0"))
			{
				flipper.removeAllViews();
				super.onPostExecute(result);
				return;
			}
			if (isResume) {
				// TODO Auto-generated method stub
				flipper.removeView(waitView);
				flipper.setDisplayedChild(rindex);
			}
			else {
				try {
					flipper.removeViews(0, viewCount);
					flipper.setDisplayedChild(0);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			super.onPostExecute(result);
		}
	}
	//转黑白图片
	public Bitmap toGrayscale(Bitmap bmpOriginal) {
		int width, height;
		height = bmpOriginal.getHeight();
		width = bmpOriginal.getWidth();    
		Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
		Canvas c = new Canvas(bmpGrayscale);
		Paint paint = new Paint();
		ColorMatrix cm = new ColorMatrix();
		cm.setSaturation(0);
		ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
		paint.setColorFilter(f);
		c.drawBitmap(bmpOriginal, 0, 0, paint);
		return bmpGrayscale;
	}
	//图片加阴影
	public void drawImageDropShadow(ImageView imageView1,Bitmap originalBitmap){
		BlurMaskFilter blurFilter = new BlurMaskFilter(3, BlurMaskFilter.Blur.OUTER);
		Paint shadowPaint = new Paint();
		shadowPaint.setMaskFilter(blurFilter);
		int[] offsetXY =new int[2];
		Bitmap shadowBitmap = originalBitmap.extractAlpha(shadowPaint,offsetXY);
		Bitmap shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true);
		Canvas c = new Canvas(shadowImage32);
		c.drawBitmap(originalBitmap, 0,0, null);
		imageView1.setImageBitmap(shadowImage32);
	}
	class BottomImgClick implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			isFling=true;
			index++;
			if (index < m_arr.size()) {
				isResume = false;
				viewCount = MenuFlipPage.this.flipper.getChildCount();
				View cView = MenuFlipPage.this.flipper.getCurrentView();
				if (!cView.equals(waitView)) {
					int num = MenuFlipPage.this.flipper.indexOfChild(cView);
					num++;
					MenuFlipPage.this.flipper.addView(waitView, num);
					viewCount++;
				}

				MenuFlipPage.this.flipper.setInAnimation(AnimationUtils.loadAnimation(
						MenuFlipPage.this, R.anim.push_top_in));
				MenuFlipPage.this.flipper.setOutAnimation(AnimationUtils.loadAnimation(
						MenuFlipPage.this, R.anim.push_top_out));
				MenuFlipPage.this.flipper.showNext();
				categoryLayout.startAnimation(AnimationUtils.loadAnimation(
						MenuFlipPage.this, R.anim.push_top_in));
				AddViewToFlipper(index);
				
			} else {
				isFling=false;
				index = m_arr.size() - 1;
			}
		}
		
	}
	class TopImgClick implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			isFling=true;
			index--;
			if (index >= 0) {
				isResume = false;
				viewCount = MenuFlipPage.this.flipper.getChildCount();
				View cView = MenuFlipPage.this.flipper.getCurrentView();
				if (!cView.equals(waitView)) {
					int num = MenuFlipPage.this.flipper.indexOfChild(cView);
					num++;
					MenuFlipPage.this.flipper.addView(waitView, num);
					viewCount++;
				}
				MenuFlipPage.this.flipper.setInAnimation(AnimationUtils.loadAnimation(
						MenuFlipPage.this, R.anim.push_bottom_in));
				MenuFlipPage.this.flipper.setOutAnimation(AnimationUtils.loadAnimation(
						MenuFlipPage.this, R.anim.push_bottom_out));
				MenuFlipPage.this.flipper.showNext();
				categoryLayout.startAnimation(AnimationUtils.loadAnimation(
						MenuFlipPage.this, R.anim.push_bottom_out));
				AddViewToFlipper(index);
			} else {
				isFling=false;
				index = 0;
			}
		}
		
	}
}
